#pragma once
#include "ThreadCache.h"
#include"Common.h"
#include"PageCache.h"
#include"ObjectPool.h"

static void* ConcurrentAlloc(size_t size)
{
	if (size > MAX_BYTES)
	{
		size_t alignSize = SizeClass::RoundUp(size);
        size_t k = alignSize >> PAGE_SHIFT;

		PageCache::GetPageObject()._pageMtx.lock();
		Span* span = PageCache::GetPageObject().ApplyPageSpan(k);
		span->_sizeObj = size;
		
		PageCache::GetPageObject()._pageMtx.unlock();

		void* ptr = (void*)(span->_pageId << PAGE_SHIFT);
		return ptr;
	}
	else
	{
	if (pTLSThreadCache == nullptr)
	{
		static ObjectPool<ThreadCache>_tcPool;
		pTLSThreadCache =_tcPool.New();
	}
	/*cout << std::this_thread::get_id() << ":" << pTLSThreadCache << endl;*/
	return pTLSThreadCache->Allocate(size);
	}
}

static void ConcurrentFree(void* ptr)
{
	Span* span = PageCache::GetPageObject().ApplyIdToSpan(ptr);
	size_t size = span->_sizeObj;

	if (size > MAX_BYTES)
	{
		PageCache::GetPageObject()._pageMtx.lock();
		PageCache::GetPageObject().GiveBackToPage(span);
		PageCache::GetPageObject()._pageMtx.unlock();
	}
	else
	{
		assert(pTLSThreadCache);
		pTLSThreadCache->Delallocate(ptr, size);
	}
}